﻿using System.Collections.Generic;
using System.Data;
using MySqlQueryToolkit.DataAccess;

namespace MySqlQueryToolkit
{
    public interface IExplainQueryRepository
    {
        IEnumerable<ExplainQueryResult> GetEntitiesFromDatabase(string query);
    }

    public class ExplainQueryRepository : Repository, IExplainQueryRepository
    {
        private readonly IDataAccess _dataAccess;

        public ExplainQueryRepository(IDataAccess dataAccess)
        {
            _dataAccess = dataAccess;
        }

        public IEnumerable<ExplainQueryResult> GetEntitiesFromDatabase(string query)
        {
            _dataAccess.CommandText = query;

            IList<ExplainQueryResult> entities = new List<ExplainQueryResult>();
            _dataAccess.ExecuteReader(reader =>
            {
                while (reader.Read())
                {
                    entities.Add(MapDataReaderToEntity(reader));
                }
            });

            return entities;
        }

        private static ExplainQueryResult MapDataReaderToEntity(IDataReader reader)
        {
            return new ExplainQueryResult
            {
                Id = GetColumnValue<long>(reader, "id", 0),
                SelectType = GetColumnValue(reader, "select_type", string.Empty),
                Table = GetColumnValue(reader, "table", string.Empty),
                Type = GetColumnValue(reader, "type", string.Empty),
                PossibleKeys = GetColumnValue(reader, "possible_keys", string.Empty),
                Key = GetColumnValue(reader, "key", string.Empty),
                KeyLength = GetColumnValue<long>(reader, "key_len", 0),
                KeyReferencedBy = GetColumnValue(reader, "ref", string.Empty),
                Rows = GetColumnValue<long>(reader, "rows", 0),
                Extra = GetColumnValue(reader, "Extra", string.Empty)
            };
        }
    }
}
